/**
 * @author: dn-jinmin/dn-jinmin
 * @doc:
 */

package main

import (
	"context"
	"fmt"
	"hash/crc32"

	red "github.com/go-redis/redis/v8"
	"github.com/xuri/excelize/v2"
)

const (
	SHEET            = "Sheet1"
	COLVAL           = "手机号码"
	RED_PHONE_EXISTS = "user:phone:exists"
)

var record map[string]string = make(map[string]string)

func parseExcel(ctx context.Context, path string) error {
	f, err := excelize.OpenFile(path)
	if err != nil {
		return err
	}
	// rows
	rows, err := f.Rows(SHEET)
	if err != nil {
		return err
	}
	defer rows.Close()
	// 计算目标数据的下标
	getColIdx := func(row []string) int {
		for i, s := range row {
			if s == COLVAL {
				return i
			}
		}
		return 0
	}

	// 迭代读取
	var (
		cur = -1
		idx = 0
	)

	for rows.Next() {
		cur++
		row, err := rows.Columns()
		if err != nil {
			return err
		}
		if cur == 0 {
			idx = getColIdx(row)
			continue
		}

		// 基于手机号码处理
		if err := sendSMS(ctx, row[idx]); err != nil {

		}
	}

	return nil
}

func sendSMS(ctx context.Context, phone string) error {
	// 检查是否重复，基于redis的
	redis := getRedis()
	v, err := redis.SetBit(ctx, RED_PHONE_EXISTS, int64(bitmapsOffset(phone)), 1).Result()
	if err != nil {
		return err
	}
	if v == 1 {
		// 存在
		fmt.Printf("手机号码 %s 已重复\n", phone)
		return nil
	}
	// 发送
	return Sms.Handler(phone)
}

var crc32q = crc32.MakeTable(0xD5828281)

func bitmapsOffset(key string) uint32 {
	crc32Phone := crc32.Checksum([]byte(key), crc32q)
	return crc32Phone & 1000000
}

func getRedis() *red.Client {
	return red.NewClient(&red.Options{
		Addr:     "",
		Password: "",
		//DB:           defaultDatabase,
		//MaxRetries:   maxRetries,
		//MinIdleConns: idleConns,
		//TLSConfig:    tlsConfig,
	})
}

var Sms = new(sms)

type sms struct {
}

func (*sms) Handler(phone string) error {
	fmt.Println("短信 := ", phone)
	return nil
}
